package Controller

import (
	"crypto/md5"
	"gin/App/Model"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"time"
)

// 访问 HTML 登录页面
func Login(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{})
}

func Index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{})
}

func IndexShow(c *gin.Context) {
	c.HTML(http.StatusOK, "listShow.html", gin.H{})
}

// 登录、注册功能
func LoginAuth(c *gin.Context) {
	loginText := c.Request.FormValue("loginText")
	loginPwd := c.Request.FormValue("loginPwd")
	text := c.Request.FormValue("text")
	pwd := c.Request.FormValue("pwd")
	pwdTo := c.Request.FormValue("pwdTo")

	//密码加密
	h := md5.New()
	password, err := h.Write([]byte(pwd))
	loginPassword, _ := h.Write([]byte(loginPwd))
	if err != nil {
		log.Fatal(err)
	}
	if len(loginText) != 0 && len(loginPwd) != 0 {
		m := Model.Login{
			Text:     loginText,
			Password: strconv.Itoa(loginPassword),
		}
		m.Login(c)
	} else if len(text) != 0 && len(pwd) != 0 && len(pwdTo) != 0 {
		if pwd != pwdTo {
			Html(c, "两次密码不一致！")
		} else {
			m := Model.Login{
				Text:       text,
				Password:   strconv.Itoa(password),
				CreateTime: int(time.Now().Unix()),
			}
			m.Register(c)
		}
	} else {
		Html(c, "填写参数不能为空！")
	}
}

func Html(c *gin.Context, msg string) {
	redirectURL := "http://127.0.0.1:8080/user/login" // 跳转链接
	message := msg
	html := `
		<!DOCTYPE html>
		<html>
		<head>
			<script>
				if (confirm("` + message + `")) {
					window.location.href = "` + redirectURL + `";
				}else{
					window.location.href = "` + redirectURL + `";
				}
			</script>
		</head>
		<body>
		</body>
		</html>
		`
	c.Data(200, "text/html; charset=utf-8", []byte(html))
}
